package cn.zb.config.security;

import com.alibaba.fastjson2.JSON;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.LockedException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * 认证异常配置类
 */
@Component
public class AuthException implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException auth) throws IOException, ServletException {
//        auth.printStackTrace();
        Map<String,Object> map = new HashMap<>();
        map.put("code",500);
        if(auth instanceof UsernameNotFoundException){
            map.put("msg",auth.getMessage());
        }else if(auth instanceof BadCredentialsException){
            map.put("msg","密码输入错误");
        }else if(auth instanceof LockedException){
            map.put("msg","账号被锁定 请联系管理员");
        }else{
            map.put("msg","认证失败");
        }
        // 设置服务器响应json
        response.setContentType("application/json;charset=utf-8");
        String json = JSON.toJSONString(map);
        response.getWriter().print(json);
    }
}
